import React, { useEffect, useState } from 'react';
import {
  Card,
  Form,
  Input,
  InputNumber,
  Select,
  Switch,
  Button,
  Upload,
  Row,
  Col,
  Space,
  message,
  Spin,
  Typography,
  Tag,
  Divider,
  Modal,
} from 'antd';
import type { UploadFile, UploadProps } from 'antd';
import {
  SaveOutlined,
  PlusOutlined,
  DeleteOutlined,
  EyeOutlined,
  UploadOutlined,
} from '@ant-design/icons';
import { useParams, useNavigate } from 'react-router-dom';
import { useAppDispatch } from '../../store';
import api from '../../utils/api';
import { setBreadcrumbs } from '../../store/slices/uiSlice';
import { ProductService } from '../../services/productService';
import { ShopService } from '../../services/shopService';
import { Product, Shop } from '../../types';

const { Title, Text } = Typography;
const { TextArea } = Input;
const { Option } = Select;

interface ProductFormData {
  name: string;
  description: string;
  price: number;
  originalPrice?: number;
  category: string;
  brand?: string;
  stock: number;
  status: 'active' | 'inactive';
  isFeatured: boolean;
  tags: string[];
  specifications: Record<string, string[]>;
  images: string[];
  shopId: string;
}

const ProductEdit: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  const [form] = Form.useForm();

  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [product, setProduct] = useState<Product | null>(null);
  const [newTag, setNewTag] = useState('');
  const [newSpecKey, setNewSpecKey] = useState('');
  const [newSpecValue, setNewSpecValue] = useState('');
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');
  const [shops, setShops] = useState<Shop[]>([]);
  const [loadingShops, setLoadingShops] = useState(false);

  const isEdit = id !== 'create';

  useEffect(() => {
    dispatch(setBreadcrumbs([
      { title: '商品管理', path: '/products' },
      { title: '商品列表', path: '/products' },
      { title: isEdit ? '编辑商品' : '添加商品' },
    ]));
  }, [dispatch, isEdit]);

  // 加载商品数据（编辑模式）
  useEffect(() => {
    if (isEdit) {
      loadProduct();
    } else {
      // 新增模式，设置默认值
      form.setFieldsValue({
        status: 'active',
        isFeatured: false,
        tags: [],
        specifications: {},
        images: [],
        stock: 0,
      });
    }

    // 加载商店列表
    loadShops();
  }, [id, isEdit, form]);

  // 加载商店列表
  const loadShops = async () => {
    try {
      setLoadingShops(true);
      const response = await ShopService.getShops({ page: 1, limit: 100 });
      setShops(response.data || []);
    } catch (error) {
      console.error('加载商店列表失败:', error);
      message.error('加载商店列表失败');
    } finally {
      setLoadingShops(false);
    }
  };

  const loadProduct = async () => {
    if (!id) return;

    try {
      setLoading(true);

      // 从API加载数据
      const productData = await ProductService.getProduct(id);
      setProduct(productData);

      // 填充表单
      form.setFieldsValue({
        name: productData.name,
        description: productData.description,
        price: productData.price,
        originalPrice: productData.originalPrice,
        category: productData.category,
        brand: productData.brand,
        stock: productData.stock,
        status: productData.status,
        shopId: productData.shop?._id || '6875ca0af9d393714e094e62',
        isFeatured: productData.isFeatured,
        tags: productData.tags || [],
        specifications: productData.specifications || {},
        images: productData.images || [],
      });

      // 设置图片列表
      const imageFileList: UploadFile[] = (productData.images || []).map((url, index) => ({
        uid: `-${index}`,
        name: `image-${index}`,
        status: 'done',
        url: url,
      }));
      setFileList(imageFileList);

    } catch (error) {
      message.error('加载商品数据失败');
      console.error('加载商品数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 保存商品
  const handleSave = async (values: ProductFormData) => {
    try {
      setSaving(true);

      // 准备提交数据
      const submitData = {
        ...values,
        shopId: values.shopId || '6875ca0af9d393714e094e62', // 使用选择的商店ID或默认Apple官方旗舰店ID
      };

      if (isEdit && id) {
        // 编辑模式
        await ProductService.updateProduct(id, submitData);
        message.success('商品更新成功');
      } else {
        // 新增模式
        await ProductService.createProduct(submitData);
        message.success('商品创建成功');
      }

      // 延迟跳转，让用户看到成功消息
      setTimeout(() => {
        navigate('/products');
      }, 1000);

    } catch (error) {
      message.error(isEdit ? '商品更新失败' : '商品创建失败');
      console.error('保存商品失败:', error);
    } finally {
      setSaving(false);
    }
  };

  // 添加标签
  const handleAddTag = () => {
    if (newTag && !form.getFieldValue('tags')?.includes(newTag)) {
      const currentTags = form.getFieldValue('tags') || [];
      form.setFieldsValue({ tags: [...currentTags, newTag] });
      setNewTag('');
    }
  };

  // 删除标签
  const handleRemoveTag = (tagToRemove: string) => {
    const currentTags = form.getFieldValue('tags') || [];
    form.setFieldsValue({
      tags: currentTags.filter((tag: string) => tag !== tagToRemove)
    });
  };

  // 添加规格
  const handleAddSpecification = () => {
    if (newSpecKey && newSpecValue) {
      const currentSpecs = form.getFieldValue('specifications') || {};
      const values = newSpecValue.split(',').map(v => v.trim()).filter(v => v);
      form.setFieldsValue({
        specifications: {
          ...currentSpecs,
          [newSpecKey]: values
        }
      });
      setNewSpecKey('');
      setNewSpecValue('');
    }
  };

  // 删除规格
  const handleRemoveSpecification = (keyToRemove: string) => {
    const currentSpecs = form.getFieldValue('specifications') || {};
    const { [keyToRemove]: removed, ...rest } = currentSpecs;
    form.setFieldsValue({ specifications: rest });
  };

  // 图片上传处理
  const handleImageChange: UploadProps['onChange'] = async ({ fileList: newFileList }) => {
    setFileList(newFileList);

    // 处理图片数据
    const imageUrls: string[] = [];

    for (const file of newFileList) {
      if (file.url) {
        // 已有的图片URL
        imageUrls.push(file.url);
      } else if (file.status === 'done' && file.response) {
        // 上传成功的文件，使用响应中的URL
        if (file.response.success && file.response.data && file.response.data.url) {
          imageUrls.push(file.response.data.url);
          // 更新文件对象的URL，以便后续使用
          file.url = file.response.data.url;
        }
      } else if (file.originFileObj && file.status !== 'done') {
        // 新上传的文件，先转换为base64用于预览
        try {
          const base64 = await getBase64(file.originFileObj);
          // 注意：这里只是用于预览，不会保存到表单数据中
          file.preview = base64;
        } catch (error) {
          console.error('转换图片失败:', error);
        }
      }
    }

    // 更新表单中的图片数据
    form.setFieldsValue({ images: imageUrls });
  };

  // 图片预览
  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as File);
    }
    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);
    setPreviewTitle(file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1));
  };

  // 上传前的处理
  const beforeUpload = (file: File) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp';
    if (!isJpgOrPng) {
      message.error('只能上传 JPG/PNG/WEBP 格式的图片!');
      return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过 2MB!');
      return false;
    }
    return true; // 允许上传
  };

  // 自定义上传处理
  const customUpload = async ({ file, onSuccess, onError }: any) => {
    try {
      const formData = new FormData();
      formData.append('file', file);

      // 使用管理员专用的上传路由
      const response = await api.upload('/admin/upload/product', formData);

      if (response.success) {
        onSuccess(response, file);
        message.success('图片上传成功');
      } else {
        throw new Error(response.message || '上传失败');
      }
    } catch (error) {
      console.error('上传失败:', error);
      onError(error);
      message.error('图片上传失败');
    }
  };

  // 将文件转换为base64
  const getBase64 = (file: File): Promise<string> =>
    new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = (error) => reject(error);
    });

  if (loading) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '400px' }}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        <Title level={3} style={{ marginBottom: '24px' }}>
          {isEdit ? '编辑商品' : '添加商品'}
        </Title>

        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
          initialValues={{
            name: '',
            description: '',
            price: 0,
            originalPrice: 0,
            category: '',
            brand: '',
            stock: 0,
            status: 'active',
            isFeatured: false,
            tags: [],
            specifications: {},
            images: [],
          }}
        >
          <Row gutter={24}>
            <Col span={16}>
              {/* 基本信息 */}
              <Card title="基本信息" size="small" style={{ marginBottom: '16px' }}>
                <Row gutter={16}>
                  <Col span={24}>
                    <Form.Item
                      label="商品名称"
                      name="name"
                      rules={[{ required: true, message: '请输入商品名称' }]}
                    >
                      <Input placeholder="请输入商品名称" />
                    </Form.Item>
                  </Col>
                  <Col span={24}>
                    <Form.Item
                      label="商品描述"
                      name="description"
                      rules={[{ required: true, message: '请输入商品描述' }]}
                    >
                      <TextArea rows={4} placeholder="请输入商品描述" />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      label="分类"
                      name="category"
                      rules={[{ required: true, message: '请选择商品分类' }]}
                    >
                      <Select placeholder="请选择分类">
                        <Option value="电子产品">电子产品</Option>
                        <Option value="服装">服装</Option>
                        <Option value="家居">家居</Option>
                        <Option value="食品">食品</Option>
                        <Option value="图书">图书</Option>
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      label="品牌"
                      name="brand"
                      rules={[{ required: true, message: '请输入品牌' }]}
                    >
                      <Input placeholder="请输入品牌" />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      label="所属商店"
                      name="shopId"
                      rules={[{ required: true, message: '请选择商店' }]}
                    >
                      <Select
                        placeholder="请选择商店"
                        loading={loadingShops}
                        showSearch
                        filterOption={(input, option) =>
                          (option?.children as unknown as string)?.toLowerCase().includes(input.toLowerCase())
                        }
                      >
                        {shops.map(shop => (
                          <Option key={shop._id} value={shop._id}>
                            {shop.name} ({shop.type === 'official' ? '官方' : shop.type === 'flagship' ? '旗舰' : '普通'})
                          </Option>
                        ))}
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col span={24}>
                    <Form.Item
                      label="商品图片"
                      name="images"
                      rules={[{ required: true, message: '请上传至少一张商品图片' }]}
                    >
                      <Upload
                        listType="picture-card"
                        fileList={fileList}
                        onChange={handleImageChange}
                        onPreview={handlePreview}
                        beforeUpload={beforeUpload}
                        customRequest={customUpload}
                        multiple
                        accept="image/*"
                      >
                        {fileList.length >= 8 ? null : (
                          <div>
                            <PlusOutlined />
                            <div style={{ marginTop: 8 }}>上传图片</div>
                          </div>
                        )}
                      </Upload>
                    </Form.Item>
                  </Col>
                </Row>
              </Card>

              {/* 价格库存 */}
              <Card title="价格库存" size="small" style={{ marginBottom: '16px' }}>
                <Row gutter={16}>
                  <Col span={8}>
                    <Form.Item
                      label="销售价格"
                      name="price"
                      rules={[{ required: true, message: '请输入销售价格' }]}
                    >
                      <InputNumber
                        style={{ width: '100%' }}
                        placeholder="0.00"
                        min={0}
                        precision={2}
                        addonBefore="¥"
                      />
                    </Form.Item>
                  </Col>
                  <Col span={8}>
                    <Form.Item label="原价" name="originalPrice">
                      <InputNumber
                        style={{ width: '100%' }}
                        placeholder="0.00"
                        min={0}
                        precision={2}
                        addonBefore="¥"
                      />
                    </Form.Item>
                  </Col>
                  <Col span={8}>
                    <Form.Item
                      label="库存数量"
                      name="stock"
                      rules={[{ required: true, message: '请输入库存数量' }]}
                    >
                      <InputNumber
                        style={{ width: '100%' }}
                        placeholder="0"
                        min={0}
                        addonAfter="件"
                      />
                    </Form.Item>
                  </Col>
                </Row>
              </Card>
            </Col>

            <Col span={8}>
              {/* 商品设置 */}
              <Card title="商品设置" size="small" style={{ marginBottom: '16px' }}>
                <Form.Item label="商品状态" name="status">
                  <Select>
                    <Option value="active">上架</Option>
                    <Option value="inactive">下架</Option>
                  </Select>
                </Form.Item>

                <Form.Item label="推荐商品" name="isFeatured" valuePropName="checked">
                  <Switch />
                </Form.Item>
              </Card>

              {/* 预览 */}
              {isEdit && (
                <Card title="操作" size="small">
                  <Space direction="vertical" style={{ width: '100%' }}>
                    <Button
                      icon={<EyeOutlined />}
                      block
                      onClick={() => navigate(`/products/${id}`)}
                    >
                      查看详情
                    </Button>
                  </Space>
                </Card>
              )}
            </Col>
          </Row>

          {/* 保存按钮 */}
          <div style={{ textAlign: 'center', marginTop: '24px' }}>
            <Space>
              <Button onClick={() => navigate('/products')}>
                取消
              </Button>
              <Button
                type="primary"
                htmlType="submit"
                loading={saving}
                icon={<SaveOutlined />}
              >
                {isEdit ? '更新商品' : '创建商品'}
              </Button>
            </Space>
          </div>
        </Form>
      </Card>

      {/* 图片预览Modal */}
      <Modal
        open={previewOpen}
        title={previewTitle}
        footer={null}
        onCancel={() => setPreviewOpen(false)}
      >
        <img alt="preview" style={{ width: '100%' }} src={previewImage} />
      </Modal>
    </div>
  );
};

export default ProductEdit;
